import { $t } from '@vben/locales';

export const getCommonShortcuts = () => {
  return [
    {
      text: $t('views.common.today'),
      value: () => {
        const start = new Date();
        start.setHours(0, 0, 0, 0);
        const end = new Date();
        end.setHours(23, 59, 59, 999);
        return [start, end];
      },
    },
    {
      text: $t('views.common.yesterday'),
      value: () => {
        const start = new Date();
        start.setDate(start.getDate() - 1);
        start.setHours(0, 0, 0, 0);
        const end = new Date(start);
        end.setHours(23, 59, 59, 999);
        return [start, end];
      },
    },
    {
      text: $t('views.common.last7Days'),
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setDate(end.getDate() - 6);
        return [start, end];
      },
    },
    {
      text: $t('views.common.last1Month'),
      value: () => {
        const today = new Date();

        const end = new Date(today);
        end.setDate(end.getDate() - 1); // 昨天

        const start = new Date(today);
        start.setMonth(start.getMonth() - 1); // 上个月的今天
        // 保证 start 的“日期”与 today 一致
        return [start, end];
      },
    },
    {
      text: $t('views.common.lastMonth'),
      value: () => {
        const now = new Date();
        const start = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        const end = new Date(
          now.getFullYear(),
          now.getMonth(),
          0,
          23,
          59,
          59,
          999,
        );
        return [start, end];
      },
    },
    {
      text: $t('views.common.last3Months'),
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setMonth(end.getMonth() - 3);
        return [start, end];
      },
    },
    {
      text: $t('views.common.last6Months'),
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setMonth(end.getMonth() - 6);
        return [start, end];
      },
    },
    {
      text: $t('views.common.last1Year'),
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setFullYear(end.getFullYear() - 1);
        return [start, end];
      },
    },
    {
      text: $t('views.common.thisMonth'),
      value: () => {
        const now = new Date();
        const start = new Date(now.getFullYear(), now.getMonth(), 1);
        const end = new Date(
          now.getFullYear(),
          now.getMonth() + 1,
          0,
          23,
          59,
          59,
          999,
        );
        return [start, end];
      },
    },
    {
      text: $t('views.common.thisQuarter'),
      value: () => {
        const now = new Date();
        const quarter = Math.floor(now.getMonth() / 3);
        const start = new Date(now.getFullYear(), quarter * 3, 1);
        const end = new Date(
          now.getFullYear(),
          quarter * 3 + 3,
          0,
          23,
          59,
          59,
          999,
        );
        return [start, end];
      },
    },
    {
      text: $t('views.common.thisYear'),
      value: () => {
        const now = new Date();
        const start = new Date(now.getFullYear(), 0, 1);
        const end = new Date(now.getFullYear(), 11, 31, 23, 59, 59, 999);
        return [start, end];
      },
    },
    {
      text: $t('views.common.lastYear'),
      value: () => {
        const now = new Date();
        const start = new Date(now.getFullYear() - 1, 0, 1);
        const end = new Date(now.getFullYear() - 1, 11, 31, 23, 59, 59, 999);
        return [start, end];
      },
    },
  ];
};

export function mergeDataByLabel(nowData: any, lastData: any, matchField: any) {
  const result = [];

  // 建立 Map，方便按 matchField 快速匹配 lastData
  const lastDataMap = new Map();
  for (const item of lastData) {
    const key = item[matchField] ?? '__null__';
    lastDataMap.set(key, item);
  }

  for (const nowItem of nowData) {
    const key = nowItem[matchField] ?? '__null__';
    const lastItem = lastDataMap.get(key) || {};

    const merged: any = {};

    // 添加当前数据（nowData）字段，前缀为 c
    for (const field in nowItem) {
      merged[`c${capitalize(field)}`] = nowItem[field];
    }

    // 添加历史数据（lastData）字段，前缀为 l
    for (const field in lastItem) {
      merged[`l${capitalize(field)}`] = lastItem[field];
    }

    result.push(merged);
  }

  return result;

  function capitalize(str: any) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
}

/**
 * 更新地址栏信息，传入对象
 * 示例调用
 * updateURLParams({ key: 'value', foo: 'bar' }); // ?key=value&foo=bar
 * updateURLParams({ baz: '123' });              // 添加 baz 参数
 * updateURLParams({ foo: null });               // 删除 foo 参数
 */

export function updateURLParams(newParams: any, useReplace = true) {
  // 获取当前 URL 和查询参数部分
  const currentUrl = window.location.href;
  const [baseUrl, queryString] = currentUrl.split('?');

  // 将现有的查询参数解析成对象
  const urlParams = new URLSearchParams(queryString || '');

  // 将传入的新参数合并到现有参数中
  Object.entries(newParams).forEach(([key, value]) => {
    if (value === null || value === undefined) {
      // 如果值为 null 或 undefined，则删除该参数
      urlParams.delete(key);
    } else {
      // 否则添加或更新该参数
      urlParams.set(
        key,
        typeof value === 'string' ? value : JSON.stringify(value),
      );
    }
  });

  // 构造新的 URL 查询参数字符串
  const newQueryString = urlParams.toString();

  // 使用 pushState 更新地址栏
  const method = useReplace ? 'replaceState' : 'pushState';
  history[method](
    null,
    '',
    newQueryString ? `${baseUrl}?${newQueryString}` : baseUrl,
  );
}

/**
 * 获取URL的地址栏参数
 */

export const getUrlParam = (
  name: string,
  defaultUrl: any = window.location.search ||
    window.location.href.split('?')[1],
) => {
  const urlParams = new URLSearchParams(defaultUrl);
  return urlParams.get(name);
};

/**
 * 判断不为null或者''
 */
export const isNotNull = (value: any) => {
  return value !== null && value !== '';
};
